/*
 * GUIClienteTeste.java
 *
 * Created on 15/05/2011, 12:19:12
 */

package gui;

import dao.DAOCliente;
import dao.ResultSetTableModel;
import javax.swing.JOptionPane;
import model.Relatorios;

/**
 * Interface que exibe os clientes já cadastrados, permitindo seleção para alteração de dados
 * @author Janio Luiz Antunes
 * @author Marcel Vinicius Kohls
 * @see http://code.google.com/p/sysdesk-java/
 *
 */
public class GUITabelaClientes extends javax.swing.JFrame {

    private DAOCliente clienteDAO = new DAOCliente();
    String pesquisar_nome=null;
    Relatorios novoRelatorio = new Relatorios();

    /** Creates new form GUIClienteTeste */
    public GUITabelaClientes() {
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jcbFiltraSituacao = new javax.swing.JComboBox();
        jLabel1 = new javax.swing.JLabel();
        jMenuBar1 = new javax.swing.JMenuBar();
        jmIncluir = new javax.swing.JMenu();
        jmAlterar = new javax.swing.JMenu();
        jmPesquisar = new javax.swing.JMenu();
        jmRelatorios = new javax.swing.JMenu();
        jmRelPorCodigo = new javax.swing.JMenuItem();
        jmRelPorNome = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("SysDesk - Clientes");
        setResizable(false);
        addWindowFocusListener(new java.awt.event.WindowFocusListener() {
            public void windowGainedFocus(java.awt.event.WindowEvent evt) {
                formWindowGainedFocus(evt);
            }
            public void windowLostFocus(java.awt.event.WindowEvent evt) {
            }
        });

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane1.setViewportView(jTable1);

        jcbFiltraSituacao.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Ativos", "Inativos", "Todos" }));
        jcbFiltraSituacao.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                jcbFiltraSituacaoItemStateChanged(evt);
            }
        });

        jLabel1.setText("Selecione a situação do cliente:");

        jmIncluir.setText("Incluir");
        jmIncluir.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jmIncluirMouseClicked(evt);
            }
        });
        jMenuBar1.add(jmIncluir);

        jmAlterar.setText("Alterar");
        jmAlterar.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jmAlterarMouseClicked(evt);
            }
        });
        jMenuBar1.add(jmAlterar);

        jmPesquisar.setText("Pesquisar");
        jmPesquisar.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jmPesquisarMouseClicked(evt);
            }
        });
        jMenuBar1.add(jmPesquisar);

        jmRelatorios.setText("Relatórios");

        jmRelPorCodigo.setText("Clientes por Código");
        jmRelPorCodigo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jmRelPorCodigoActionPerformed(evt);
            }
        });
        jmRelatorios.add(jmRelPorCodigo);

        jmRelPorNome.setText("Clientes por Nome");
        jmRelPorNome.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jmRelPorNomeActionPerformed(evt);
            }
        });
        jmRelatorios.add(jmRelPorNome);

        jMenuBar1.add(jmRelatorios);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jcbFiltraSituacao, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(323, Short.MAX_VALUE))
            .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 572, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(25, 25, 25)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jcbFiltraSituacao, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 305, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    /**
     * Monta uma tabela especifica baseada no banco de clientes
     */
    private void atualizaTabela(){
        try {
            String[] TitulosColunas = {"Codigo", "Nome", "Ativo"};
            jTable1.setModel(new ResultSetTableModel(clienteDAO.getListaClientes(jcbFiltraSituacao.getSelectedIndex(), pesquisar_nome), TitulosColunas));
            System.out.println("Selecionado"+ jcbFiltraSituacao.getSelectedIndex());
            jTable1.updateUI();
            jTable1.repaint();
        } catch (Exception e) {
            System.out.println("erro: "+e.getMessage());
        }
    }

    /**
     *
     * Quando a tela estiver abrindo atualiza a tabela
     */
    private void formWindowGainedFocus(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowGainedFocus
        atualizaTabela();
    }//GEN-LAST:event_formWindowGainedFocus

    /**
     *
     * Quando for alterado o filtro (Ativo, Inativo, Todos) atualiza a tabela
     */
    private void jcbFiltraSituacaoItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_jcbFiltraSituacaoItemStateChanged
        atualizaTabela();
    }//GEN-LAST:event_jcbFiltraSituacaoItemStateChanged

    /**
     *
     * Abre a interface de cadastro para um novo clienteDAO
     */
    private void jmIncluirMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jmIncluirMouseClicked
        GUICadastroClientes cadastroClientes = new GUICadastroClientes();
        cadastroClientes.setVisible(true);
    }//GEN-LAST:event_jmIncluirMouseClicked

    /**
     * Evento que abre a interface de cadastro de clientes com os dados selecionados para alteração
     * @param codigoSelecionado
     */
    private void jmAlterarMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jmAlterarMouseClicked
        try{
            int codigoSelecionado = Integer.parseInt(jTable1.getValueAt(jTable1.getSelectedRow(), 0).toString());

            GUICadastroClientes cadastroClientes = new GUICadastroClientes();
            cadastroClientes.setCodigoSelecionado(codigoSelecionado);
            cadastroClientes.setVisible(true);
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, "Erro: Selecione um cliente ("+e.getMessage()+")");
        }
    }//GEN-LAST:event_jmAlterarMouseClicked

    /**
     *
     * Evento que faz a pesquisa de um cliente já cadastrado
     */
    private void jmPesquisarMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jmPesquisarMouseClicked

        pesquisar_nome = String.valueOf(JOptionPane.showInputDialog(this, "Informe um cliente para a pesquisa:"));

    }//GEN-LAST:event_jmPesquisarMouseClicked
    /**
     *
     * Evento que carrega o relatório de clientes ordenado por código
     */
    private void jmRelPorCodigoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jmRelPorCodigoActionPerformed
        novoRelatorio.gerarNovoRelatorio("src/relatorios/clientes_codigo.jasper");
    }//GEN-LAST:event_jmRelPorCodigoActionPerformed

    /**
     * 
     * Evento que carrega o relatório de clientes ordenado por nome
     */
    private void jmRelPorNomeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jmRelPorNomeActionPerformed
        novoRelatorio.gerarNovoRelatorio("src/relatorios/clientes_nome.jasper");
    }//GEN-LAST:event_jmRelPorNomeActionPerformed

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new GUITabelaClientes().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JComboBox jcbFiltraSituacao;
    private javax.swing.JMenu jmAlterar;
    private javax.swing.JMenu jmIncluir;
    private javax.swing.JMenu jmPesquisar;
    private javax.swing.JMenuItem jmRelPorCodigo;
    private javax.swing.JMenuItem jmRelPorNome;
    private javax.swing.JMenu jmRelatorios;
    // End of variables declaration//GEN-END:variables

}
